package com.wwdx.controller.admin;

import com.wwdx.controller.base.BaseController;
import com.wwdx.model.WwdxBookChapterModel;
import com.wwdx.model.WwdxBookModel;
import com.wwdx.model.WwdxCdKeyModel;
import com.wwdx.utils.ConstantHolder;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author liguoliang
 * @date 2017/10/12
 */
@Controller
@RequestMapping("/system/wwdx_book")
public class WwdxBookController extends BaseController{

    /**
     * 列表
     */
    @RequestMapping("/list")
    public ModelAndView list(WwdxBookModel model,String phase,Long pid,
                             @RequestParam(value = "page", defaultValue = "1") int page,
                             @RequestParam(value = "rows",defaultValue = "10") int rows) {
        
        ModelAndView mav = new ModelAndView();
        List<WwdxBookModel> wwdxBookModels = wwdxBookService.selectModelList(model, page, rows);
        /*Set<String> classes = new HashSet<>(),tabs = new HashSet<>();
        wwdxBookModels.forEach(wwdxBookModel -> {
            List<WwdxBookClassifyModel> bookClassifyModels = wwdxBookClassifyService.getByBookId(wwdxBookModel.getBookid());
            bookClassifyModels.forEach(wwdxBookClassifyModel -> {
                //标签
                wwdxBookClassifyModel = wwdxBookClassifyService.getByPid(wwdxBookClassifyModel.getPid());
                tabs.add(wwdxBookClassifyModel.getName());
                //分类
                wwdxBookClassifyModel = wwdxBookClassifyService.getByPid(wwdxBookClassifyModel.getPid());
                classes.add(wwdxBookClassifyModel.getName());
            });
            wwdxBookModel.setClasses(classes.toString());
            wwdxBookModel.setTabs(tabs.toString());
            classes.clear();
            tabs.clear();
        });*/
        mav.addObject("listSize", wwdxBookService.selectModelCount(model));
        mav.addObject("list", wwdxBookModels);
        mav.addObject("phase",phase);
        mav.addObject("pid",pid);
        return mav;
    }

    /**
     * 书籍下的章节分页
     */
    @RequestMapping("/chapter_list")
    public ModelAndView chapterlist(Long bookid) {
        ModelAndView mav = new ModelAndView();
        List<WwdxBookChapterModel> bookChapterList = wwdxBookChapterService.findBookChapterList(bookid);
        mav.addObject("listSize",  bookChapterList.size());
        mav.addObject("list",  bookChapterList);
        mav.addObject("bookid",bookid);
        return mav;
    }

    /**
     * 新增
     */
    @RequestMapping("/create")
    public ModelAndView create() {
        return new ModelAndView();
    }

    /**
     * 修改页面
     */
    @RequestMapping("/edit")
    public ModelAndView edit(Long id) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("model",wwdxBookService.getById(id));
        return mav;
    }

    /**
     * 保存新增
     */
    @RequestMapping("/save")
    public String save(WwdxBookModel model, HttpServletRequest request){
        this.execute(request,model);
        model.setBookid(System.currentTimeMillis() / 1000);
        model.setGmtCreated(new Date());
        model.setGmtModified(new Date());
        wwdxBookService.save(model);
        return "redirect:/system/wwdx_book/list";
    }

    private void execute(HttpServletRequest request,WwdxBookModel model){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        //书籍封面 | 思维导图（大） | 思维导图（小）| 横幅 | 小课详情图片
        String bookImg = "BookImg",mappingImg = "MappingImg",mappingSamllImg = "MappingSmallImg",
                bannerImg = "BannerImg" ,smallLessonImg = "SmallLessonImage";
        fileMap.forEach((k,file)->{
            if (file.getSize() > 0) {
                if (bookImg.equalsIgnoreCase(file.getName())) {
                    model.setBookimg(super.upload(file,directory + ConstantHolder.Constant.COVER));
                }
                if (mappingImg.equalsIgnoreCase(file.getName())) {
                    model.setMapping_img(super.upload(file, directory + ConstantHolder.Constant.COVER));
                }
                if (mappingSamllImg.equalsIgnoreCase(file.getName())) {
                    model.setMapping_small_img(super.upload(file, directory + ConstantHolder.Constant.COVER));
                }
                if (bannerImg.equalsIgnoreCase(file.getName())) {
                    model.setBanner(super.upload(file, directory + ConstantHolder.Constant.COVER));
                }
                if (smallLessonImg.equalsIgnoreCase(file.getName())) {
                    model.setSmallLessonImg(super.upload(file, directory + ConstantHolder.Constant.COVER));
                }
            }
        });
    }

    /**
     * 修改保存
     */
    @RequestMapping("/update")
    public String update(WwdxBookModel model, HttpServletRequest request){
        this.execute(request,model);
        model.setGmtModified(new Date());
        wwdxBookService.update(model);
        return "redirect:/system/wwdx_book/list";
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresRoles("super")
    public String delete(Long id) {
        WwdxBookModel wwdxBookModel = wwdxBookService.getById(id);
        wwdxBookService.delete(wwdxBookModel);
        return "redirect:/system/wwdx_book/list";
    }

    /**
     * 添加赠一得一专区书籍
     */
    @RequestMapping("/addgiveonebook")
    public String addgiveonebook(String phase,Long bookid,RedirectAttributes attributes) {
        String bookListKey = String.format(ConstantHolder.GIVEONE_BOOK_LIST, phase);
        listOperations.rightPush(bookListKey,bookid.toString());
        attributes.addAttribute("phase",phase);
        return "redirect:/system/wwdx_giveone/book_list";
    }
    
    /**
     * 删除赠一得一专区书籍
     */
    @RequestMapping("/delgiveonebook")
    public String delgiveonebook(String phase,Long bookid,RedirectAttributes attributes) {
        String bookListKey = String.format(ConstantHolder.GIVEONE_BOOK_LIST, phase);
        listOperations.remove(bookListKey,0,bookid.toString());
        attributes.addAttribute("phase",phase);
        return "redirect:/system/wwdx_giveone/book_list";
    }

    /**
     * 添加书籍Online
     */
    @RequestMapping("/addbookonline")
    public String addbookonline(Long bookid) {
        zSetOperations.add(ConstantHolder.BOOK_ONLINE_ZSET,bookid.toString(),valueOperations.increment(ConstantHolder.BOOK_ONLINE_PHASE,1));
        return "redirect:/system/wwdx_book_online/list";
    }

    /**
     * 删除书籍Online
     */
    @RequestMapping("/delbookonline")
    public String delbookonline(Long bookid) {
        zSetOperations.remove(ConstantHolder.BOOK_ONLINE_ZSET,bookid.toString());
        return "redirect:/system/wwdx_book_online/list";
    }

    /**
     * 添加兑换码
     */
    @RequestMapping("/createCDKEY")
    public ModelAndView createCDKEY(Long bookid){
        ModelAndView mv = new ModelAndView();
        mv.addObject("bookid",bookid);
        return mv;
    }

    /**
     * 添加兑换码
     * @param loop 轮循次数
     */
    @RequestMapping("/addCDKEY")
    public String addCDKEY(Long bookid,Integer loop){
        WwdxCdKeyModel model = new WwdxCdKeyModel();
        model.setProduct_id(bookid);
        model.setType(2);
        wwdxCdKeyService.addCDKEY(model, loop);
        return "redirect:/system/wwdx_cdkey/list";
    }
}